//
//  KCSession.m
//  KConnect
//
//  Created on 19/03/09.
//  Copyright 2009 Xtreme Labs Inc. All rights reserved.
//


static NSInteger kBufferSize      = 10;
static NSString *kApiURL          = @"http://api.kontagent.net/api/v1/";
static NSString *kApiTestURL      = @"http://api.test.kontagent.net/api/v1/";


#if DEBUG
#define KCLog(X,Y) NSLog(X,Y)
#else
#define KCLog(X,Y)
#endif

#import "KCSession.h"


static KCSession *session = nil;


@interface KCSession(Private)

- (id)initWithApiKey:(NSString*)key;

@end


@implementation KCSession

@synthesize apiKey;

+ (KCSession*)sessionWithApiKey:(NSString*)apiKey
{
  @synchronized(self)
  {
    if (session == nil)
    {
      session = [[KCSession alloc] initWithApiKey:apiKey];
    }
  }
  
  return session;
}

+ (KCSession*)session
{
  return session;
}

- (id)initWithApiKey:(NSString*)key
{
  if(self = [super init])
  {
    apiKey = [key copy];
    connections = [[NSMutableArray alloc] initWithCapacity:kBufferSize];
    testing = NO;
  }
  return self;
}

- (void)send:(KCMessage*)message
{
  NSString *msgUrl = [[message URL] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  NSString *urlString;
  
  if (testing)
    urlString = [NSString stringWithFormat:@"%@/%@/%@", kApiTestURL, apiKey, msgUrl];
  else
    urlString = [NSString stringWithFormat:@"%@/%@/%@", kApiURL, apiKey, msgUrl];

  KCLog(@"get %@", urlString);

  NSURL *url = [NSURL URLWithString:urlString];
  URLCacheConnection * connection = [[URLCacheConnection alloc] initWithURL:url delegate:self];
  [connections addObject:connection];
  [connection release];
}

- (void)useTesting:(BOOL)test
{
  testing = test;
}

#pragma mark URL Connection Handlers

- (void) connectionDidNotStart:(URLCacheConnection*) theConnection
{
  KCLog(@"Could not start %@", [[theConnection.theRequest URL] absoluteString]);
  [connections removeObject:theConnection];
}

- (void) connectionDidFail:(URLCacheConnection *)theConnection
{
  KCLog(@"Could not connect %@", [[theConnection.theRequest URL] absoluteString]);
  [connections removeObject:theConnection];  
}

- (void) connectionDidFinish:(URLCacheConnection *)theConnection
{
  KCLog(@"Finished %@", [[theConnection.theRequest URL] absoluteString]);
  KCLog(@"Returned %@", [[NSString alloc] initWithData:[theConnection receivedData] encoding:NSUTF8StringEncoding]);
  [connections removeObject:theConnection];
}


#pragma mark NSObject override

- (void)dealloc {
  if ([session isEqual:self]) {
    session = nil;
  }
  
  [apiKey release];  
  [super dealloc];
}
   
@end
